package com.tinyspot.concrete.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Tinyspot
 * @date 2023-01-06 22:13
 */
public class DateUtil {

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(timeStampToDateTime(date.getTime()));

        System.out.println(parseToDateTime("2023-01-06 22:34:55"));
        System.out.println(parseToDate("2023-01-06"));
        System.out.println(parseDateTime(new Date()));
        System.out.println(parseDate(new Date()));
    }

    public static final Long ONE_HOUR_MILLISECONDS = 60 * 60 * 1000L;
    public static final Long ONE_DAY_SECONDS = 24 * 60 * 60L;
    public static final Long ONE_DAY_MILLISECONDS = 24 * 60 * 60 * 1000L;
    public static final Long ONE_LIFE = 100L * 365 * 24 * 60 * 60 * 1000;

    /**
     * 时间格式
     */
    public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    public static String parseDate(Date date) {
        return parseDateByFormat(date, DEFAULT_DATE_FORMAT);
    }

    public static String parseDateTime(Date date) {
        return parseDateByFormat(date, DEFAULT_DATETIME_FORMAT);
    }

    public static Date parseToDate(String date) {
        return parseToDateByFormat(date, DEFAULT_DATE_FORMAT);
    }

    public static Date parseToDateTime(String date) {
        return parseToDateByFormat(date, DEFAULT_DATETIME_FORMAT);
    }

    /**
     * 时间戳转为时间格式
     * @param value 时间戳，比如 1673015695603
     * @return 比如 2023-01-06 22:34:55
     */
    public static String timeStampToDateTime(Long value) {
        if (value == null) {
            return null;
        }
        Date date = new Date(value);
        return parseDateTime(date);
    }

    public static String timeStampToDateTime(String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        try {
            Date date = new Date(Long.parseLong(value));
            return parseDateTime(date);
        } catch (Exception e) {
            return null;
        }
    }

    private static String parseDateByFormat(Date date, String dateFormat) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }

    private static Date parseToDateByFormat(String date, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

}
